

var fuel_requests = {

    init: function() {
        this.configureTabs();
        this.configureButtons();
        this.configureSearch();
        this.configureMenus();
    },
    
    configureButtons: function() {
        $("#btn_new_request").click(function(e) {
            e.preventDefault();
            
            var url = $(this).attr("href");
            var query = "";
            
            $.post(url, query, function(data) {
                core.showFlyout({
                    title: "New Permit Request",
                    content: data,
                    load: function() {
                        fuel_requests.setupDatePickers();
                    },
                    close: function() {
                        fuel_requests.reloadRequests();
                    }
                });
            });
        });
        
        $(".buttons #edit-request.active").live('click', function(e) {
            e.preventDefault();
            
            var url = $(this).data("url") + "/" + $(this).data("id");
            var query = "request_id=" + $(this).data("id");
            
            $.post(url, query, function(data) {
                core.showFlyout({
                    title: "Editing Fuel Request",
                    content: data,
                    load: function() {
                        $("#flyout form input[type=submit]").val("Update Request");
                        
                        fuel_requests.setupDatePickers();
                    },
                    close: function(data) {
                        $("#requests_table tbody tr.selected").click();
                    }
                });
            });
        });
        
        $(".buttons #delete-request.active").live('click', function(e) {
            e.preventDefault();
            
            if( !confirm('Delete Selected Fuel Request and Move To Archive?') ) {
                return;
            }
            
            var url = $(this).data('url') + "/" + $(this).data('id');
            var query = "request_id=" + $(this).data('id');
            
            $.post(url, query, function() {
                fuel_requests.removeSelected('open');
            },'json');
        });
    },
    
    configureTabs: function() {
        $( "#tabs" ).bind( "tabsload", function(event, ui) {
            fuel_requests.setupGridBindings(ui.panel);
        });
        
        $(".pane-footer li").live('click', function() {
            var url = $(this).data('url');
            
            $.ajax({
                url: url,
                type: 'get',
                success: function(data) {
                    var panel = $(".ui-tabs-panel").get( $("#tabs").tabs('option','selected') );
                    $(panel).html(data);
                    
                    fuel_requests.setupGridBindings(panel);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            }); 
        });
    },
    
    configureSearch: function() {
        function doSearch(url, term) {
            var query = "term=" + term+"&filter="+$("#search_term").val();
            $("#open_perms").html("Searching ...");
            
            $.ajax({
                url: url,
                data: query,
                //dataType: 'json',
                type: 'get',
                success: function(data) {
                    //$("#open_perms").html(data);
                    var panel = $(".ui-tabs-panel").get( $("#tabs").tabs('option','selected') );
                    $(panel).html(data);
                    
                    fuel_requests.setupGridBindings(panel);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        }
        
        $("#search_term").change(function() {
            var option = this.options[this.selectedIndex];
             
            $("input.search").attr("placeholder", $(option).data('placeholder'));
        }).css({
            'font-size': '11px'
        });
        
        $("input.search").keyup(function(e) {
            if( e.keyCode == 13 ) {
                doSearch( $(this).data('url'), $(this).val() );
            }
        });
    },
    
    configureMenus: function() {
        
        $("#actions .menu li").click(function() {
            
            // only active menus should be processed
            if( !$(this).parents('.menu_button').hasClass('active') ) {
                return;
            }
            
            var element = this;
            var el_id = this.id;
            var request_id = $(this).parents(".menu_button").data('id');
            
            var url = $(this).data('url') + "/" + request_id;
            var type = $(this).data('type') == null ? 'json' : $(this).data('type');
            var query = "fuel_request_id=" + request_id;
            
            if( $(this).data('status') != null && $(this).data('status') != "" ) {
                query += "&status=" + $(this).data('status');
            }
            
            $.ajax({
                url: url,
                data: query,
                dataType: type,
                type: 'post',
                success: function(data) {
                    fuel_requests.processMenuSelection(data, element);
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        });
        
        $("#selected .menu li").click(function(e) {
            
            e.preventDefault();
            
            var ids = [];
            $("#requests_table tr input:checked").each(function() {
                ids.push( $(this).val() );
            });
            
            if( ids.length > 0 ) {
                if( !confirm("Are you sure you want to change the status of the selected permits?") ) {
                    return;
                }
            }
            
            else {
                alert("Please select permits to alter using the checkboxes");
                return;
            }
            
            var url = $("#selected.menu_button").data('url');
            var query = "status=" + $(this).data('status') + "&ids=" + ids;
            
            $.ajax({
                url: url,
                data: query,
                dataType: 'json',
                type: 'post',
                success: function(data) {
                    $("#requests_table tbody tr input:checked").each(function() {
                        if( ids.indexOf( $(this).val() ) > -1 ) {
                            if( data.open ) {    
                                fuel_requests.removeChecked('closed');
                            }
                    
                            else {
                                fuel_requests.removeChecked('open');
                            }
                        } 
                    });
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            });
        });
    },
    
    processMenuSelection: function(data, menu) {
        var el_id = menu.id;
        
        switch(el_id) {
            case 'send-request':
                core.showFlyout({
                    title: 'Send Request To CAA',
                    content: data,
                    load: function() {
                        core.setupButtonsAndMenus();
                    },
                    close: function() {
                        $("#requests_table tr.selected .status").html('wfs');
                    }
                });
                            
                break;
                            
            case 'enter-confirmation':
                core.showDialog({
                    title: 'Enter Fueling Request Confirmation',
                    content: data,
                    close: function() {
                        $("#requests_table tr.selected .status").html('approved');
                        $("#requests_table tr.selected").click();
                    }
                });
                            
                break;
                            
            case 'confirmation-form':
                core.showFlyout({
                    title: 'Preview Request Form',
                    content: data,
                    load: function() {
                        $(".flyout_content #print-form").click(function() {
                            window.open( $(this).data('url') );
                        });
                                    
                        $(".flyout_content #download-form").click(function() {
                            if( 'humane' in window ) {
                                humane.info('Generating Forwarding Form PDF');
                            }
                                        
                            var $this = $(this);
                            setTimeout(function() {
                                window.location.href = $this.data('url');
                            }, 1000);
                                        
                        });
                                    
                        $(".flyout_content #send-form").click(function() {
                            $.get( $(this).data('url'), function(data) {
                                core.showDialog({
                                    title: 'Sending Forwarding Form',
                                    content: data,
                                    width: 800,
                                    height: 550
                                });
                            });
                                        
                        });
                    },
                    close: function(data) {
                        $("#requests_table tr.selected .permit-number").html( data.Permit.permit_number );
                        $("#requests_table tr.selected .status").html('approved');
                        $("#requests_table tr.selected").click();
                    }
                });
                break;
                            
            case 'attach_original_request':
                core.showDialog({
                    title: 'Add/View Request Attachments',
                    content: data,
                    load: function() {
                        Attachments.init({
                            submit: function() {
                                // reshow the menu
                                $(menu).click();
                            }
                        });
                    }
                });
                break;

            case 'cancel-request':
            case 'hold-request':
            case 'close-request':
                core.showDialog({
                    title: 'Change Request Status',
                    content: data,
                    width: 600,
                    height: 400,
                    close: function(data) {
                        console.log(data);
                        $("#requests_table tr.selected .status").html( data.status );
                                    
                        if( data.status == "closed" ) {
                            fuel_requests.removeSelected('open');
                        }
                    }
                });
                break;
        }
    },
    
    setupGridBindings: function(panel) {
        $(panel).find("#requests_table tbody tr").click(function() {
                
            $(".buttons li").addClass('active').data("id", $(this).data('id'));
            /*if( $(this).parents('#requests_table').hasClass('open') || $(this).parents('#requests_table').hasClass('uplifted') ) {
                
            } else {
                $(".buttons li").removeClass('active');
            }*/

            var url = $(this).data("url");

            $.get(url, function(data) {
                $(".details_block .details_pane").html(data);
            });
        });
        
        $(panel).find("#requests_table tbody tr:first").click();
    },
    
    
    setupDatePickers: function() {
        setTimeout(function() {
            
            $(".datetime").datetimepicker({ 
                showButtonPanel: false,
                showOn: "both",
                buttonImage: "../img/core/ico-12.png",
                buttonImageOnly: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm'
            });
            
            $("#application_dt").datetimepicker({ 
                showButtonPanel: true,
                showOn: "both",
                buttonImage: "../img/core/ico-12.png",
                buttonImageOnly: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:00'
            });
            
            $(".date_input input.date").datetimepicker({
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:ss',
                changeMonth: true,
                changeYear: true
            });
        
            $("input.location").autocomplete({
                source: $("#iata-auto-complete-source").val(), // specified in URLs element
                minLength: 2
            });
        }, 500);
    },
    
    reloadRequests: function() {
        $("#tabs").tabs('load', $("#tabs").tabs('option', 'selected'));
    },
    
    removeSelected: function(status) {
        $("#requests_table." + status + " tr.selected").remove();
        $(".buttons li").removeClass('active');
        
        var count = 1;
        $("#request_table." + status + " .numbers").each(function() {
            $(this).html(count++ + ".");
        });
    }
};

$(document).ready(function() {
    fuel_requests.init();
});
